package com.meida.module.product.provider.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.meida.common.enums.YesNoEnum;
import com.meida.common.mybatis.base.service.impl.BaseServiceImpl;
import com.meida.common.mybatis.entity.EntityMap;
import com.meida.common.mybatis.model.GetModel;
import com.meida.common.mybatis.model.ListModel;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.common.mybatis.query.CriteriaSave;
import com.meida.common.mybatis.query.CriteriaUpdate;
import com.meida.common.security.OpenHelper;
import com.meida.common.utils.FlymeUtils;
import com.meida.module.product.client.entity.ProdProduct;
import com.meida.module.product.client.entity.ProdShop;
import com.meida.module.product.provider.mapper.ProdShopMapper;
import com.meida.module.product.provider.service.ProdShopService;
import com.meida.module.system.client.entity.SysCompany;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 实现类
 *
 * @author flyme
 * @date 2019-06-17
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ProdShopServiceImpl extends BaseServiceImpl<ProdShopMapper, ProdShop> implements ProdShopService {


    @Override
    public ResultBody setProdShop(CriteriaSave cs) {
        Long companyId = OpenHelper.getCompanyId();
        cs.put("companyId", companyId);
        //设置店铺ID和企业ID一致便于一个企业对应一个店铺
        cs.put("shopId", companyId);
        ProdShop prodShop = getById(companyId);
        ProdShop entity = cs.getEntity(ProdShop.class);
        if (FlymeUtils.isNotEmpty(entity)) {
            entity.setShopState(1);
            entity.setVisitCount(0);
            entity.setLookCount(0);
        }
        if (FlymeUtils.isNotEmpty(prodShop)) {
            if (prodShop.getShopState().equals(2)) {
                entity.setShopState(10);
            }
            CriteriaUpdate cu = new CriteriaUpdate();
            cu.eq("shopId", companyId);
            update(entity, cu);
        } else {
            save(entity);
        }
        return ResultBody.msg("设置成功").data(entity);
    }

    @Override
    public ProdShop findByCompanyId(Long companyId) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq(true, "companyId", companyId);
        return getOne(qw);
    }


    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultBody getByCompany(GetModel model) {
        Long companyId = OpenHelper.getCompanyId();
        CriteriaQuery cq = new CriteriaQuery(model, ProdShop.class);
        cq.select(ProdShop.class, "shopId", "shopName", "shopLogo", "linkMan", "shopState", "remark", "linkTel", "businessScope", "areaId", "cityId", "proId", "shopDesc", "shopAddress", "companyId");
        cq.eq(ProdShop.class, "companyId", companyId);
        return baseGet(cq);
    }


    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultBody listByCompany(ListModel listModel) {
        Long companyId = OpenHelper.getCompanyId();
        CriteriaQuery<EntityMap> cq = new CriteriaQuery(listModel, ProdShop.class);
        cq.select(ProdShop.class, "*");
        cq.eq(ProdShop.class, "companyId", companyId);
        return baseList(cq);
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultBody beforePageList(CriteriaQuery<ProdShop> cq, ProdShop prodShop, EntityMap requestMap) {

        cq.select(SysCompany.class, "companyName");
        //维度
        String lat = requestMap.get("lat");
        //经度
        String lon = requestMap.get("lon");
        //排序字段
        String order = requestMap.get("order");
        //排序方式
        String sort = requestMap.get("sort");
        cq.select(ProdShop.class, "*");
        if (FlymeUtils.allNotNull(lon, lat)) {
            //计算距离
            cq.addSelect("IFNULL(distance(" + lat + ", " + lon + ", lat, lon),0) distance");
            //设置排序
            if (FlymeUtils.isNotEmpty(order) && "distance".equals(order)) {
                cq.orderBy(order, sort);
            } else {
                cq.orderByAsc("distance");
            }

        }
        if (FlymeUtils.isNotEmpty(order)) {
            cq.orderBy(order, sort);
        }
        cq.likeByField(ProdShop.class, "linkMan");
        cq.likeByField(ProdShop.class, "shopName");
        cq.eq(ProdShop.class, "shopState");
        cq.createJoin(SysCompany.class);
        cq.eq(ProdShop.class, "typeId");
        return ResultBody.ok();
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public List<EntityMap> listRecommend(CriteriaQuery cq, int count, boolean collecon) {
        cq.select(ProdShop.class, "shopId", "shopName", "shopLogo", "shopImage");
        if (collecon) {
            setCollecon(cq);
        }
        cq.eq("recommend", YesNoEnum.YES.getCode());
        cq.orderByDesc("createTime");
        cq.last("limit " + count);
        return selectEntityMap(cq);
    }

    @Override
    public List<EntityMap> listNearby(EntityMap params, int count, boolean collecon) {
        //维度
        String lat = params.get("lat");
        //经度
        String lon = params.get("lon");
        //排序字段
        String order = params.get("order");
        //排序方式
        String sort = params.get("sort");
        //是否推荐
        Integer recommend = params.getInt("recommend", YesNoEnum.YES.getCode());
        CriteriaQuery cq = new CriteriaQuery(ProdShop.class);
        cq.select(ProdShop.class, "shopId", "shopName", "shopLogo", "shopImage");
        if (collecon) {
            setCollecon(cq);
        }
        if (FlymeUtils.allNotNull(lon, lat)) {
            cq.addSelect("IFNULL(distance(" + lat + ", " + lon + ", lat, lon),0) distance");
            if (FlymeUtils.isEmpty(order)) {
                //默认按距离正序排列
                cq.orderByAsc("distance");
            }
        }
        cq.eq("recommend", recommend);
        if (FlymeUtils.isNotEmpty(order)) {
            cq.orderBy(order, sort);
        }
        if (count > 0) {
            cq.last("limit " + count);
        }
        return selectEntityMap(cq);
    }

    /**
     * 设置收藏标记
     *
     * @param cq
     */
    private void setCollecon(CriteriaQuery<ProdProduct> cq) {
        //是否添加收藏标记
        Long userId = OpenHelper.getUserId();
        if (FlymeUtils.isNotEmpty(userId)) {
            cq.addSelect("(select count(targetId) from sys_collecon sc where sc.targetId=shop.shopId and targetEntity='ProdShop' and userId=" + userId + ") colleconTag");
        }
    }


    @Override
    public Boolean updateVisitCount(Long shopId, Integer num) {
        CriteriaUpdate cu = new CriteriaUpdate();
        cu.setSql(true, "visitCount=visitCount+" + num);
        cu.ge("visitCount", 0);
        cu.eq(true, "shopId", shopId);
        return update(cu);
    }

    @Override
    public ResultBody updateLookCount(Long shopId, Integer num) {
        CriteriaUpdate cu = new CriteriaUpdate();
        cu.setSql(true, "lookCount=lookCount+" + num);
        cu.ge("lookCount", 0);
        cu.eq(true, "shopId", shopId);
        Boolean up = update(cu);
        return ResultBody.msg("");
    }

}
